﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RoccaStore.Utils
{
    public class HashUtils
    {
        #region ID Hashing

        public static string index = "abcdefghijklmnopqrstuvwxyz-0123456789";

        public static string Encode(long Number)
        {
            string res = String.Empty;

            for (int j = (int)Math.Floor(Math.Log(Number) / Math.Log(index.Length)); j >= 0; j--)
            {
                res += index.Substring((int)(Math.Floor(Number / bcpow(index.Length, j)) % index.Length), 1);
            }

            return Reverse(res);
        }

        public static long Decode(string Id)
        {
            string str = Reverse(Id);
            long res = 0;
            int end = str.Length - 1;

            for (int j = 0; j <= end; j++)
            {
                res = res + (long)(index.IndexOf(str.Substring(j, 1)) * bcpow(index.Length, end - j));
            }
            return res;
        }

        public static double bcpow(double inputa, double inputb)
        {
            return Math.Floor(Math.Pow(inputa, inputb));
        }

        public static string Reverse(string s)
        {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }

        #endregion

        #region Data Hashing

        public static string EncodeDynamicHash(dynamic data, string key)
        {
            string dataString = Newtonsoft.Json.JsonConvert.SerializeObject(data);
            return SecurityUtils.Encrypt(dataString, key);
        }

        public static dynamic DecodeDynamicHash(string data, string key)
        {
            string dataString = SecurityUtils.Decrypt(data, key);
            return (dynamic)Newtonsoft.Json.JsonConvert.DeserializeObject(dataString);
        }

        #endregion
    }
}
